﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ExamAnalysis.Model;
using ExamAnalysis.Core;
using Ext.Net;
using System.IO;

namespace ExamAnalysis.Input
{
    public partial class InputExamInfo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Store1.DataSource = new ExamAnalysisDataContext().ExamGroup.ToList();
                Store1.DataBind();
                Store3.DataSource = new ExamAnalysisDataContext().ExamInfo.ToList();
                Store3.DataBind();
            }
        }

        protected void Store1_load(Object sender, EventArgs e)
        {
        }

        protected void Store1_BeforeChange(object sender, BeforeStoreChangedEventArgs e)
        {

            string json = e.DataHandler.JsonData;

            ExamAnalysisDataContext db = new ExamAnalysisDataContext();

            StoreDataHandler dataHandler = new StoreDataHandler(json);
            List<ExamGroup> data = dataHandler.ObjectData<ExamGroup>();

            foreach (ExamGroup supplier in data)
            {
                switch (e.Action)
                {
                    case StoreAction.Destroy:
                        db.ExamGroup.Attach(supplier);
                        db.ExamGroup.DeleteOnSubmit(supplier);
                        break;
                    case StoreAction.Update:
                        db.ExamGroup.Attach(supplier);
                        db.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, supplier);
                        break;
                    case StoreAction.Create:
                        db.ExamGroup.InsertOnSubmit(supplier);
                        break;
                }
            }

            db.SubmitChanges();

            if (e.Action != StoreAction.Destroy)
            {
                foreach (ExamGroup supplier in data)
                {
                    e.ResponseRecords.Add(supplier);
                }
            }

            e.Cancel = true;
        }

        protected void Store3_BeforeChange(object sender, BeforeStoreChangedEventArgs e)
        {

            string json = e.DataHandler.JsonData;

            ExamAnalysisDataContext db = new ExamAnalysisDataContext();

            StoreDataHandler dataHandler = new StoreDataHandler(json);
            List<ExamInfo> data = dataHandler.ObjectData<ExamInfo>();

            foreach (ExamInfo supplier in data)
            {
                switch (e.Action)
                {
                    case StoreAction.Destroy:
                        db.ExamInfo.Attach(supplier);
                        db.ExamInfo.DeleteOnSubmit(supplier);
                        break;
                    case StoreAction.Update:
                        db.ExamInfo.Attach(supplier);
                        db.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, supplier);
                        break;
                    case StoreAction.Create:
                        db.ExamInfo.InsertOnSubmit(supplier);
                        break;
                }
            }

            db.SubmitChanges();

            if (e.Action != StoreAction.Destroy)
            {
                foreach (ExamInfo supplier in data)
                {
                    e.ResponseRecords.Add(supplier);
                }
            }

            e.Cancel = true;
        }

        protected void Store4_BeforeChange(object sender, BeforeStoreChangedEventArgs e)
        {
            RowSelectionModel sm = this.GridPanel3.GetSelectionModel() as RowSelectionModel;
            int examId = 0;
            if (sm.SelectedRows.Count != 0)
                examId = int.Parse(sm.SelectedRows[0].RecordID);

            string json = e.DataHandler.JsonData;

            ExamAnalysisDataContext db = new ExamAnalysisDataContext();

            StoreDataHandler dataHandler = new StoreDataHandler(json);
            List<ExamItemsGroup> data = dataHandler.ObjectData<ExamItemsGroup>();

            foreach (ExamItemsGroup supplier in data)
            {
                switch (e.Action)
                {
                    case StoreAction.Destroy:
                        db.ExamItemsGroup.Attach(supplier);
                        db.ExamItemsGroup.DeleteOnSubmit(supplier);
                        break;
                    case StoreAction.Update:
                        db.ExamItemsGroup.Attach(supplier);
                        db.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, supplier);
                        break;
                    case StoreAction.Create:
                        supplier.ExamID = examId;
                        db.ExamItemsGroup.InsertOnSubmit(supplier);
                        break;
                }
            }
            db.SubmitChanges();
            //if (e.Action != StoreAction.Destroy)
            //{
            //    foreach (ExamItemsGroup supplier in data)
            //    {
            //        e.ResponseRecords.Add(supplier);
            //    }
            //}
            e.Cancel = true;
        }


        protected void btnUpload_DirectClick(object sender, Ext.Net.DirectEventArgs e)
        {
            string UploadFile = "";
            if (this.FileField.HasFile)
            {
                UploadFile = this.FileField.PostedFile.FileName.ToString();
                int FileSize = Int32.Parse(this.FileField.PostedFile.ContentLength.ToString());
                if (FileSize > 5 * 1024 * 1024)
                {
                    X.Msg.Alert("提示信息", "上传文件过大！").Show();
                    return;
                }
                string strFileName = Path.GetExtension(this.FileField.PostedFile.FileName).ToLower();//获取文件后缀
                if (!(strFileName == ".xls" || strFileName == ".xlsx"))
                {
                    X.Msg.Alert("提示信息", "文件格式不正确！").Show();
                    return;
                }

                Random ran = new Random();
                string sNewName = DateTime.Now.ToString(@"yyyyMMddHHmmss") + ran.Next(100, 999)
                  + Path.GetExtension(this.FileField.PostedFile.FileName);
                string strPath = Server.MapPath("~/FileUpload/" + sNewName);
                if (!Directory.Exists(Path.GetDirectoryName(strPath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(strPath));
                }
                this.FileField.PostedFile.SaveAs(strPath);
                //
                FileInfo file = new FileInfo(strPath);
                X.Msg.Alert("提示信息", String.Format("成功添加{0}个考试", InputUtil.inputExamFromExcel(file))).Show();
                file.Delete();
                Store3.DataSource = new ExamAnalysisDataContext().ExamInfo.ToList();
                Store3.DataBind();
            }
            else
            {
                X.Msg.Alert("提示信息", "请选择您要上传的文件!").Show();
            }
        }

        protected void examBind()
        {
            ExamAnalysisDataContext db = new ExamAnalysisDataContext();
            var list = from s in db.ExamInfo
                       select s;
            Store2.DataSource = list;
            Store2.DataBind();
        }

        protected void groupExamBind()
        {

        }

        protected void testClick(object sender, DirectEventArgs e)
        {

        }
        protected void Store2_Refresh(object sender, StoreReadDataEventArgs e)
        {
            ExamAnalysisDataContext db = new ExamAnalysisDataContext();
            string id = e.Parameters["ExamGroupID"];
            var list = from s in db.ExamInfo
                       select s;
            Store2.DataSource = list;
            Store2.DataBind();
        }
        protected void RowSelect(object sender, DirectEventArgs e)
        {
            ExamAnalysisDataContext db = new ExamAnalysisDataContext();
            int ExamGroupID = 0;
            try
            {
                ExamGroupID = int.Parse(e.ExtraParams["ExamGroupID"]);
            }
            catch (FormatException ex)
            {
                return;
            }

            if (ExamGroupID != -1)
            {
                var list = from s in db.ExamInGroup
                           where s.ExamGroupID == ExamGroupID
                           select new { s.ExamInfo.ExamName, s.ExamID, s.ExamGroupID };
                Store2.DataSource = list;
                Store2.DataBind();
            }
        }

        protected void RowSelect_ExamInfo(object sender, DirectEventArgs e)
        {
            ExamAnalysisDataContext db = new ExamAnalysisDataContext();
            int examId = 0;
            try
            {
                examId = int.Parse(e.ExtraParams["ExamID"]);
            }
            catch (FormatException ex)
            {
                return;
            }

            if (examId != -1)
            {
                var list = from s in db.ExamItemsGroup
                           where s.ExamID == examId
                           select s;
                Store4.DataSource = list;
                Store4.DataBind();
            }
        }
        protected void Button5_DirectClick(object sender, DirectEventArgs e)
        {

            RowSelectionModel sm = this.GridPanel2.GetSelectionModel() as RowSelectionModel;
            int examId = 0;
            int groupId = 0;
            if (sm.SelectedRows.Count != 0)
                examId = int.Parse(sm.SelectedRows[0].RecordID);
            else return;

            RowSelectionModel sm2 = this.GridPanel1.GetSelectionModel() as RowSelectionModel;
            if (sm2.SelectedRows.Count != 0)
                groupId = int.Parse(sm2.SelectedRows[0].RecordID);
            else return;
            ExamAnalysisDataContext db = new ExamAnalysisDataContext();
            db.ExamInGroup.DeleteAllOnSubmit(from eg in db.ExamInGroup
                                             where eg.ExamID == examId && eg.ExamGroupID == groupId
                                             select eg);
            db.SubmitChanges();
            var list = from s in db.ExamInGroup
                       where s.ExamGroupID == groupId
                       select new { s.ExamInfo.ExamName, s.ExamID, s.ExamGroupID };
            Store2.DataSource = list;
            Store2.DataBind();

        }

        protected void Button6_DirectClick(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = this.GridPanel2.GetSelectionModel() as RowSelectionModel;
            int examId = 0;
            int groupId = 0;
            if (sm.SelectedRows.Count != 0)
                examId = int.Parse(sm.SelectedRows[0].RecordID);
            else return;

            RowSelectionModel sm2 = this.GridPanel1.GetSelectionModel() as RowSelectionModel;
            if (sm2.SelectedRows.Count != 0)
                groupId = int.Parse(sm2.SelectedRows[0].RecordID);
            else return;
            ExamAnalysisDataContext db = new ExamAnalysisDataContext();
            db.ExamInGroup.DeleteAllOnSubmit(from eg in db.ExamInGroup
                                             where eg.ExamGroupID == groupId
                                             select eg);
            db.SubmitChanges();
            var list = from s in db.ExamInGroup
                       where s.ExamGroupID == groupId
                       select new { s.ExamInfo.ExamName, s.ExamID, s.ExamGroupID };
            Store2.DataSource = list;
            Store2.DataBind();
        }

        protected void Button7_DirectClick(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = this.GridPanel3.GetSelectionModel() as RowSelectionModel;
            int examId = 0;
            int groupId = 0;
            if (sm.SelectedRows.Count != 0)
                examId = int.Parse(sm.SelectedRows[0].RecordID);
            else return;

            RowSelectionModel sm2 = this.GridPanel1.GetSelectionModel() as RowSelectionModel;
            if (sm2.SelectedRows.Count != 0)
                groupId = int.Parse(sm2.SelectedRows[0].RecordID);
            else return;
            ExamAnalysisDataContext db = new ExamAnalysisDataContext();
            db.ExamInGroup.InsertOnSubmit(new ExamInGroup()
            {
                ExamID = examId,
                ExamGroupID = groupId
            });
            try
            {
                db.SubmitChanges();
            }
            catch (Exception ex)
            {

                return;

            }
            var list = from s in db.ExamInGroup
                       where s.ExamGroupID == groupId
                       select new { s.ExamInfo.ExamName, s.ExamID, s.ExamGroupID };
            Store2.DataSource = list;
            Store2.DataBind();
        }

        protected void Button8_DirectClick(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = this.GridPanel3.GetSelectionModel() as RowSelectionModel;
            int examId = 0;
            int groupId = 0;
            if (sm.SelectedRows.Count != 0)
                examId = int.Parse(sm.SelectedRows[0].RecordID);
            else return;

            RowSelectionModel sm2 = this.GridPanel1.GetSelectionModel() as RowSelectionModel;
            if (sm2.SelectedRows.Count != 0)
                groupId = int.Parse(sm2.SelectedRows[0].RecordID);
            else return;
            ExamAnalysisDataContext db = new ExamAnalysisDataContext();
            var ls = from s in db.ExamInfo
                     select s.ExamID;
            db.ExamInGroup.DeleteAllOnSubmit(db.ExamInGroup.Where(t => t.ExamGroupID == groupId));
            db.SubmitChanges();
            foreach (int i in ls)
            {
                db.ExamInGroup.InsertOnSubmit(new ExamInGroup() { ExamGroupID = groupId, ExamID = i });
            }

            db.SubmitChanges();
            var list = from s in db.ExamInGroup
                       where s.ExamGroupID == groupId
                       select new { s.ExamInfo.ExamName, s.ExamID, s.ExamGroupID };
            Store2.DataSource = list;
            Store2.DataBind();
        }

        protected void uploadExamItem_DirectClick(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = this.GridPanel_ItemGroup.GetSelectionModel() as RowSelectionModel;
            int groupId = 0;
            if (sm.SelectedRows.Count != 0)
                groupId = int.Parse(sm.SelectedRows[0].RecordID);
            else
            {
                X.Msg.Alert("通知", "请在“高级管理”中选择相应试题组").Show();
                return;
            }
            string UploadFile = "";
            if (this.FileField.HasFile)
            {
                UploadFile = this.FileField.PostedFile.FileName.ToString();
                int FileSize = Int32.Parse(this.FileField.PostedFile.ContentLength.ToString());
                if (FileSize > 5 * 1024 * 1024)
                {
                    X.Msg.Alert("提示信息", "上传文件过大！").Show();
                    return;
                }
                string strFileName = Path.GetExtension(this.FileField.PostedFile.FileName).ToLower();//获取文件后缀
                if (!(strFileName == ".xls" || strFileName == ".xlsx"))
                {
                    X.Msg.Alert("提示信息", "文件格式不正确！").Show();
                    return;
                }

                Random ran = new Random();
                string sNewName = DateTime.Now.ToString(@"yyyyMMddHHmmss") + ran.Next(100, 999)
                  + Path.GetExtension(this.FileField.PostedFile.FileName);
                string strPath = Server.MapPath("~/FileUpload/" + sNewName);
                if (!Directory.Exists(Path.GetDirectoryName(strPath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(strPath));
                }
                this.FileField.PostedFile.SaveAs(strPath);
                //
                FileInfo file = new FileInfo(strPath);
                X.Msg.Alert("提示信息", String.Format("成功添加{0}个题目", InputUtil.inputExamItemsFromExcel(file, groupId))).Show();
                file.Delete();
            }
            else
            {
                X.Msg.Alert("提示信息", "请选择您要上传的文件!").Show();
            }
        }

    }
}